/**
 * 设备地图展示的地图组件
 */
import React, { Component } from 'react';
import mapOnLoad from '../../../utils/map';
import { randomStr } from '../../../utils/util';
import fireIcon from '../../../assets/fireIcon.png';
import Sidebar from './sidebar';
// isFireAlarm
const styles = {
	height: { height: '650px' },
	main: {
		position: 'relative'
	}
};

let Marker = null;
let LngLat = null;

const iconUrl = 'http://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png';
const styleStr = 'position: absolute;left: 0;width: 100%;text-align: center;color: #fff;';

class Map extends Component {
	constructor(props, context) {
		super(props, context);
		this.key = randomStr();
		this.state = {
			id: 0, // 投放点id
			deviceCount: 0
		};
	}

	componentDidMount() {
		mapOnLoad(this.init);
	}

	componentDidUpdate(prevProps, prevState) {
		this.inited && prevProps.list !== this.props.list ? this.renderMarker() : null;
	}

	onMarkerClick = e => {
		const { clickMarker } = this.props;
		const data = e.target.getExtData();
		clickMarker({ id: data.id, deviceCount: data.deviceCount });
		this.map.setZoomAndCenter(13, e.target.getPosition());
	}

	init = () => {
		const { clickMarker } = this.props;
		Marker = window.AMap.Marker;
		LngLat = window.AMap.LngLat;
		this.map = new window.AMap.Map(this.key, {
			resizeEnable: true,
			zoom: 5
		});
		this.map.on('click', () => clickMarker({ id: null, deviceCount: 0 }));
		this.renderMarker();
		this.inited = true;
	}

	renderMarker() {
		const { list } = this.props;
		this.markers ? this.map.remove(this.markers) : null;
		this.markers = list.map(d => {
			const style = d.isFireAlarm ? `${styleStr}color:#000;` : styleStr;
			const marker = new Marker({
				position: new LngLat(d.longitude, d.latitude),
				map: this.map,
				clickable: true,
				content: `<div><img src="${d.isFireAlarm ? fireIcon : iconUrl}"><span style="${style}">${d.deviceCount}</span></div>`,
				title: `${d.deviceCount}台`,
				extData: d
			});
			marker.on('click', this.onMarkerClick);
			return marker;
		});
		this.map.setFitView();
	}

	render() {
		const { queryData, sidebarProps } = this.props;
		return (
			<div style={styles.main}>
				<div style={styles.height} id={this.key} />
				{sidebarProps.id ? <Sidebar {...sidebarProps} data={queryData} /> : null}
			</div>
		);
	}
}

export default Map;
